# coding: utf8
import platform
import sys
import commands
import socket
import re


def check_command_exec(command_str):
    print u"开始执行...\n{0}".format(command_str)
    exec_result = commands.getstatusoutput(command_str)
    if exec_result[0] != 0:
        print exec_result[1]
        return sys.exit()
    print u"执行{0}成功...\n".format(command_str)
    return

def check_ip_input(tip_str):
    while True:
        # The address of the interface to bind to:
        input_str = raw_input(tip_str).strip()
        try:
            if not input_str:
                input_str = '0.0.0.0'
            else:
                socket.inet_aton(input_str)
            break
        except:
            print u'请输入ip'
            continue
    return input_str

def file_content_sub(config_file, old, new):
    with open(config_file, 'r') as f:
        lines = f.readlines()
    with open(config_file, 'w') as f_w:
        # Explicit is better than implicit. 外显优于内隐。
        for line in lines:
            f_w.write(re.sub(old, new, line))


if __name__ == '__main__':
    print u"开始安装salt配置管理工具...\n"
    system_info = platform.dist()
    host_name = socket.gethostname()
    if system_info[0] != "centos":
        print u'检查系统版本, 需要centos'
        sys.exit(1)
    else:
        while True:
            install_type = raw_input(u'Choose node salt type \n1) master\n2) minion\nDefault is salt-minion\n').strip()
            if install_type not in ['1', '2', '']:
                continue
            else:
                install_type = "master" if install_type == '1' else 'minion'
                break

        sys_version = system_info[1].split('.')[0]
        if commands.getstatusoutput('yum repolist|grep salt-latest')[0] !=0:
            yum_repo = "curl http://47.90.8.193/salt-latest.repo -o /etc/yum.repos.d/salt-latest.repo"
            check_command_exec(yum_repo)
            check_command_exec("yum clean expire-cache")

        check_command_exec("yum -y  install salt-{0}".format(install_type))
        if install_type == "master":
            check_command_exec("yum -y install salt-{0}".format("minion"))

        print u"安装成功~\n开始配置...\n"
        if install_type == 'master':
            master_config_file = "/etc/salt/master"
            interface = check_ip_input(tip_str=u"Salt-master listen ip\n Default is \"0.0.0.0\":")
            file_content_sub(config_file=master_config_file, old=r'#interface:.*', new="interface: {0}".format(interface))
        minion_config_file = "/etc/salt/minion"
        salt_master = check_ip_input(tip_str=u"Input Salt_master ip:")
        file_content_sub(config_file=minion_config_file, old=r'#master:.*', new="master: {0}".format(salt_master))
        print "Set salt minion minion_id. Default use hostname"
        with open('/etc/salt/minion_id','w') as f:
            f.write(host_name)
            print u"写入成功...\n"

        print u"配置成功...\n"
        print u"开始启动...\n"
        if sys_version == '6':
            if install_type == 'master':
                check_command_exec('/etc/init.d/salt-master restart')
            check_command_exec('/etc/init.d/salt-minion restart')
        elif sys_version == '7':
            if install_type == 'master':
                check_command_exec('systemctl restart salt-master')
            check_command_exec('systemctl restart salt-minion')
        print u"启动成功...\n"